package com.itheima.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice//异常处理声明
public class GlobalExceptionHandler {
    //全局异常处理器 处理异常：SQLIntegrityConstraintViolationException
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handleException(SQLIntegrityConstraintViolationException ex){
        //获取异常信息，获得异常描述和注册用户名
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
          String username=  message.split(" ")[2];
            return R.error("用户名" + username+"已存在");
        }
        return R.error("系统繁忙");
    }

    @ExceptionHandler(DeleteException.class)
    public R<String> deleteException(DeleteException deleteException){
        String message = deleteException.getMessage();
        return R.error(message);
    }
}





//作用：主要是处理全局异常，遇到重复创建等异常捕获并抛出会给出错误信息